const express = require('express')
const app = express()
const port = 3000;
const jwt = require('./dao/jwt')

var server = app.listen(8082);
var io = require('socket.io').listen(server);
//引入解析req.body插件
const bodyParser = require('body-parser')
require('./dao/socket.js')(io);

app.all("*", function (req, res, next) {
    // 设置允许跨域的域名,*代表允许任意域名跨域
    res.header('Access-Control-Allow-Origin', '*');
    // 允许的header类型
    res.header('Access-Control-Allow-Headers', 'origin,X-Requested-With,content-type,Accept');
    // 跨域允许的请求方式
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', 'DELETE,PUT,POST,GET,OPTIONS');
    res.header('X-Powered-By', '3.2.1');
    res.header('Content-Type', 'application/json;charset=utf-8');
    if (req.method.toLowerCase() == 'options')
        res.send(200); // 让options 尝试请求快速结束
    else
        next();
})
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true })) //文件上传大小限制
app.use(bodyParser.json({ limit: "50mb" })) //文件上传大小限制
app.use(express.static(__dirname + '/data'))
//token判断
app.use((req, res, next) => {
    if (typeof (req.body.token) != 'undefined') {
        let tokenMatch = jwt.verifyToken(token)
        if (tokenMatch == 1) {
            next()
        } else {
            //验证不通过 跳转到登录页
            res.send({ status: 300 })
        }
    } else {
        next()
    }
})
app.use((err, req, res, next) => {
    res.status(500).json({ message: err.message })
    next()
})
require('./router/index')(app)
require('./router/files')(app)
app.get('/', (req, res) => {
    res.send('hello')
})
//404 页面
app.use((req, res, next) => {
    let err = new Error('not found')
    err.status = 404
    next(err)
})
//出现错误处理
app.use((err, req, res, next) => {
    res.status(err.status || 500)
    res.send(err.message)
})
app.listen(port, () => {
    console.log('listen');

})